export const fileUtil = {
	/* 获取压缩以后的文件对象  
		config.size:压缩多少kb
		config.width:压缩多少kb
		config.height:压缩多少kb
		config.quality:压缩多少kb
	 callback  放回file*/
	getCompress:function(file,config,callback){
		if(!config.size){
			//默认大于1M压缩
			config.size = 1025;
		}
		if(file.size/1024 > config.size) { 
			fileUtil.photoCompress(file,config,function(base64){
				callback( fileUtil.dataURLtoFile(base64,file.name) );
			})
		}else{
			callback(file);
		}
	},
	dataURLtoFile(dataurl, filename) {//将base64转换为文件
		var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
		while(n--){
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new File([u8arr], filename, {type:mime});
	},
	photoCompress :function(file,config,callback){
		var ready=new FileReader();
		/*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
		ready.readAsDataURL(file);
		ready.onload=function(){
			var re=this.result;
			fileUtil.canvasDataURL(re,config,callback)
		}
	},
	canvasDataURL :function(path, config, callback){
		var img = new Image();
		img.src = path;
		img.onload = function(){
			var that = this;
			// 默认按比例压缩
			var w = that.width,
				h = that.height,
				scale = w / h;
			w = config.width || w;
			h = config.height || (w / scale);
			var quality = config.quality || 0.7;  // 默认图片质量为0.7
			//生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			// 创建属性节点
			var anw = document.createAttribute("width");
			anw.nodeValue = w;
			var anh = document.createAttribute("height");
			anh.nodeValue = h;
			canvas.setAttributeNode(anw);
			canvas.setAttributeNode(anh);
			ctx.drawImage(that, 0, 0, w, h);
			// 图像质量
			if(config.quality && config.quality <= 1 && config.quality > 0){
				quality = config.quality;
			}
			// quality值越小，所绘制出的图像越模糊
			var base64 = canvas.toDataURL('image/jpeg', quality);
			// 回调函数返回base64的值
			callback(base64);
		}
	}
}


